package android.pot.com.smartcar.ui.home.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.entity.DefaultSiteEntity;
import android.pot.com.smartcar.entity.ProductDetailEntity;
import android.pot.com.smartcar.fragment.MethodDialogView;
import android.pot.com.smartcar.fragment.PayDialogView;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.TipToast;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.PayResult;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhaoshilu on 2017/11/27.
 */
public class ProductBuyActivity extends SwipeBackActivity {

    private TextView tv_method,tv_site,tv_person;

    private View rl_select_method;

    private EditText et_site,et_person,et_phone;

    private TextView tv_num,tv_price,tv_yunfei,tv_final_price;

    private ProductDetailEntity detailEntity;

    private int num = 1;

    private double singlePrice = 0.00;

    private double yunfeiPrice = 0.00;

    private int receiveMethod = 2;

    private View ll_fei;

    private DefaultSiteEntity siteEntity;

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_buy);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();
        addListener();
        initData();
    }


    @Override
    protected void initView() {
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("购买商品");
        api = WXAPIFactory.createWXAPI(this, "wx17ec252bfac28859");
        ll_fei = findViewById(R.id.ll_fei);
        rl_select_method =  findViewById(R.id.rl_select_method);
        tv_method =  (TextView) findViewById(R.id.tv_method);
        et_site = (EditText) findViewById(R.id.et_site);
        et_person = (EditText) findViewById(R.id.et_person);
        tv_site = (TextView) findViewById(R.id.tv_sites);
        tv_person = (TextView) findViewById(R.id.tv_persons);

        et_phone = (EditText) findViewById(R.id.et_phone);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_yunfei = (TextView) findViewById(R.id.tv_yunfei);
        tv_final_price = (TextView) findViewById(R.id.tv_final_price);
        Bundle bundle =  getIntent().getExtras();
        detailEntity= (ProductDetailEntity) bundle.getSerializable("detail");
        singlePrice = Double.parseDouble(detailEntity.getSpecial_price());
        yunfeiPrice = Double.parseDouble(detailEntity.getFare_money());
        tv_price.setText(TextCheckUtil.formate2Money(detailEntity.getSpecial_price()));
        tv_yunfei.setText(TextCheckUtil.formate2Money(detailEntity.getFare_money()));
        Double d = Double.parseDouble(detailEntity.getSpecial_price())+Double.parseDouble(detailEntity.getFare_money());
        tv_final_price.setText(d+"");



    }


    @Override
    protected void addListener() {
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToFinishActivity();
            }
        });
        rl_select_method.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MethodDialogView dialogView = new MethodDialogView(ProductBuyActivity.this);
                dialogView.show(getSupportFragmentManager(),"dialogView");
                dialogView.setMethodClickListener(new MethodDialogView.OnMethodClickListener() {
                    @Override
                    public void methodClick(int method) {
                        if (method == 0){
                            receiveMethod = 2;
                            tv_method.setText("邮寄");
                            tv_site.setText("收货地址");
                            tv_person.setText("收货人");
                            et_site.setHint("请填写详细地址");
                            et_person.setHint("请填写收货人姓名");
                            yunfeiPrice = Double.parseDouble(detailEntity.getFare_money());
                            tv_final_price.setText((singlePrice*num + yunfeiPrice)+"");
                            ll_fei.setVisibility(View.VISIBLE);
                            //设置可编辑状态
                            et_site.setFocusableInTouchMode(true);
                            et_site.setFocusable(true);
                            et_site.requestFocus();
                            try {
                                et_phone.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_phone()));
                                et_site.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_address()));
                                et_person.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_name()));
                            }catch (Exception e){
                                et_phone.setText("");
                                et_site.setText("");
                                et_person.setText("");
                            }
                        }else{
                            receiveMethod = 1;
                            tv_method.setText("自取");
                            tv_site.setText("取货地址");
                            tv_person.setText("取货人");
                            et_site.setHint("请填写取货地址");
                            et_person.setHint("请填写取货人姓名");
                            yunfeiPrice = 0.00;
                            tv_final_price.setText((singlePrice*num + yunfeiPrice)+"");
                            ll_fei.setVisibility(View.GONE);
                            //设置不可编辑状态
                            et_site.setFocusable(false);
                            et_site.setFocusableInTouchMode(false);
                            try {
                                et_phone.setText(TextCheckUtil.CheckString(siteEntity.getPick_phone()));
                                et_site.setText(TextCheckUtil.CheckString(siteEntity.getPick_address()));
                                et_person.setText(TextCheckUtil.CheckString(siteEntity.getPick_name()));

                            }catch (Exception e){
                                et_phone.setText("");
                                et_site.setText("");
                                et_person.setText("");
                            }

                        }
                    }
                });
            }
        });
        findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num ++;
                tv_num.setText(num+"");
                tv_price.setText((singlePrice*num)+"");
                tv_final_price.setText((singlePrice*num + yunfeiPrice)+"");
            }
        });
        findViewById(R.id.tv_reduce).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (num > 1){
                    num --;
                    tv_num.setText(num+"");
                    tv_price.setText((singlePrice*num)+"");
                    tv_final_price.setText((singlePrice*num + yunfeiPrice)+"");
                }
            }
        });
        findViewById(R.id.bt_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                generate_orders();

            }
        });

    }

    @Override
    protected void initData() {
        getDefaultSite();
    }

    private void getDefaultSite(){
        Map<String,String> params = new HashMap<>();
        params.put("goods_id",detailEntity.getId());
        LoadingTool.StartLoading(this);
        Action.get().buy_goods(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,final JSONObject response) {
                LoadingTool.EndLoading(ProductBuyActivity.this);
                try {
                    siteEntity = GsonUtil.getObject(response.toString(), DefaultSiteEntity.class);
                    et_phone.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_phone()));
                    et_site.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_address()));
                    et_person.setText(TextCheckUtil.CheckString(siteEntity.getReceipt_name()));
                }catch (Exception e){

                }
            }
        });
    }
    private void generate_orders(){
        if (receiveMethod == 2){
            if (TextUtils.isEmpty(et_site.getText().toString())){
                TipToast.show("请填写收货人地址");
                return;
            }
            if (TextUtils.isEmpty(et_person.getText().toString())){
                TipToast.show("请填写收货人姓名");
                return;
            }
        }else{
            if (TextUtils.isEmpty(et_site.getText().toString())){
                TipToast.show("请填写取货地址");
                return;
            }
            if (TextUtils.isEmpty(et_person.getText().toString())){
                TipToast.show("请填写取货人姓名");
                return;
            }
        }

        if (TextUtils.isEmpty(et_phone.getText().toString())){
            TipToast.show("请填写联系人电话");
            return;
        }

        Map<String,String> params = new HashMap<>();
        params.put("goods_id",detailEntity.getId());
        params.put("buy_type",receiveMethod+"");
        params.put("pick_name",et_person.getText().toString());
        params.put("pick_address",et_site.getText().toString());
        params.put("pick_phone",et_phone.getText().toString());
        params.put("buy_num",tv_num.getText().toString());
        LoadingTool.StartLoading(this);
        Action.get().generate_orders(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,final JSONObject response) {
                LoadingTool.EndLoading(ProductBuyActivity.this);
                PayDialogView dialogView = new PayDialogView(ProductBuyActivity.this);
                dialogView.show(getSupportFragmentManager(),"dialogView");
                dialogView.setMethodClickListener(new PayDialogView.OnMethodClickListener() {
                    @Override
                    public void methodClick(int method) {
                        String orderId= "";
                        try {
                            orderId = response.getString("order_ns");
                            pay(method,orderId);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private void pay(final int method, final String orderId){
        Map<String,String> params = new HashMap<>();
        params.put("order_ns",orderId);
        if (method == 0){
            params.put("pay_type","2");
        }else{
            params.put("pay_type","1");
        }
        LoadingTool.StartLoading(this);
        Action.get().pay(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message, final JSONObject response) {
                LoadingTool.EndLoading(ProductBuyActivity.this);
                if (method == 0){
                    weixinPay(response);
                }else{
                    try {
                        String orderInfo = response.getString("data");
                        alipay(orderInfo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void weixinPay(JSONObject json) {

        PayReq req = new PayReq();
        try {
            req.appId = json.getString("appid");
            req.partnerId = json.getString("partnerid");
            req.prepayId = json.getString("prepayid");
            req.nonceStr = json.getString("noncestr");
            req.timeStamp = json.getString("timestamp");
            req.packageValue = json.getString("package");
            req.sign = json.getString("sign");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }
    private void alipay(final String orderInfo){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ProductBuyActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo,true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_AUTH_FLAG = 2;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        TipToast.show("支付成功");
                        startAct(ProductBuyActivity.this,ProductDetailActivity.class);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {

                }
                default:
                    break;
            }
        };
    };

}